<template>
  <section>
    <!--高级查询工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getDictionaryDetailsPlus">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <!--数据展示列表,展示的数据是domain中的字段-->
    <el-table :data="dictionaryDetails" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="types_id" label="数据类型编号" width="400"  sortable>
      </el-table-column>
      <el-table-column prop="name" label="名称" width="400" sortable>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页+批量删除工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          layout="sizes, prev, pager, next, jumper, total"
          @current-change="handleCurrentChange"
          @size-change="sizeChange"
          :page-size="pageSize"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :pager-count="pagerCount"
          :total="total"
          style="float:right;">
      </el-pagination>
    </el-col>

    <!--新增或编辑界面-->
    <el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="类型id" prop="types_id">
          <!--在下拉框中，prop绑定的值和v-model绑定的值一致，才能做必填校验-->
          <!--
             :key   下拉列表行的唯一键 id，有几个不同的id就会有几个下拉选项，如果id相同，会覆盖前一个
             :label  选中之后展示在下拉列表框中的值
             后面那两个span是在下拉列表中展示的值
             :value  选中之后绑定给模型层的
             value-key="id"  如果我们要传递对象给后端，这里一定增加value-key

          -->
          <el-select v-model="editForm.types_id"  placeholder="请选择">
            <el-option
                v-for="item in dictionaryTypes"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.sn }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
import { getDictionaryDetailListPage, removeDictionaryDetail, batchRemoveDictionaryDetail, editDictionaryDetail, addDictionaryDetail } from '../../api/api';

export default {
  data() {
    return {
      filters: {
        keyword: ''
      },
      dictionaryTypes:[],
      title: "",
      dictionaryDetails:[],
      total: 0,
      currentPage: 1,
      pageSize: 8,
      pagerCount: 5,//页码超过5时折叠后续页码，用...显示
      pageSizes: [2, 4, 8, 10, 20, 50],//每页展示条数下拉框候选项
      listLoading: false,
      sels: [],//列表选中行

      //编辑界面是否显示
      editFormVisible: false,
      editLoading: false,
      //校验规则
      editFormRules: {
        name: [
          /*
            * required：必填
            * trigger：触发条件
            * blur：失去焦点
            * */
          {required: true, message: '请输入名称', trigger: 'blur'}
        ],
        types_id: [
          /*
          * required：必填
          * trigger：触发条件
          * blur：失去焦点
          * */
          {required: true, message: '请选择编号', trigger: ['blur','change']}
        ]
      },

      //在编辑界面可能要显示以下数据
      editForm: {
        id: null,
        name: "",
        types_id: null
      }
    }
  },
  methods: {
    //页面展示数据条数变化时重新查询
    sizeChange(size) {
      this.pageSize = size
      this.getDictionaryDetailsPlus();
    },
    //页码变化时重新查询
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getDictionaryDetails();
    },
    //给高级查询单独搞一个方法
    getDictionaryDetailsPlus() {
      //高级查询完成之后，需要定位页码到第一页
      this.currentPage = 1
      this.getDictionaryDetails()
    },
    //获取数据字典明细列表
    getDictionaryDetails() {
      //封装高级查询+分页的参数
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.filters.keyword
      };
      this.listLoading = true;
      this.$http.post("/dicd", para)
          .then(result => {
            //关闭忙等列表
            this.listLoading = false;
            //得到的就是PageList
            result = result.data;
            this.total = result.total;
            this.dictionaryDetails = result.rows;
          })
          .catch(result => {
            console.log(result);
            this.$message({
              message: '系统繁忙，稍后重试！',
              type: 'error'
            });
          })
    },
    //删除一个
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '温馨提示', {
        type: 'warning'
      }).then(() => {
        //确定要删除
        this.listLoading = true;
        //发起删除请求
        this.$http.delete("/dicd/" + row.id)
            .then(result => {
              console.log(result)
              this.listLoading = false;
              result = result.data//AjaxResult
              if (!result.success) {
                this.$message({
                  message: result.message,
                  type: 'error'
                });
              }
              //删除成功
              this.$message({
                message: result.message,
                type: 'success'
              });
              //数据删除成功后要定位到第一页
              this.currentPage = 1;
              this.getDictionaryDetails();
            })
            .catch(result => {
              //后台删除失败
              this.$message({
                message: '系统繁忙，稍后重试！',
                type: 'error'
              });
            })
      }).catch(() => {
        //取消或者关闭弹窗
        this.$message({
          message: '取消或者关闭弹窗！',
          type: 'info'
        });
      });
    },
    //批量删除
    batchRemove: function () {
      //得到要删除的数据的id数组
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '温馨提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //前端发送批量删除的请求
        this.$http.patch("/dicd",ids)
            .then(result=>{
              this.listLoading = false;
              this.$message({
                message: "删除成功",
                type: 'success'
              });
              this.getDictionaryDetailsPlus()
            })
            .catch(result=>{
              console.log(result)
              this.$message({
                message: result.data.message,
                type: 'error'
              });
            })
      }).catch(() => {
        this.$message({
          message:"已经取消删除",
          type: 'info'
        });
      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.title = "编辑";
      //弹出修改模态框
      this.editFormVisible = true;
      //克隆本行数据到一个新的对象，用于回显
      //如果不克隆直接修改row的话，由于表单中的属性和模型层是双向绑定的，会直接修改页面展示数据，但实际上数据库没有改变，页面刷新就失效
      this.editForm = Object.assign({}, row);
    },
    //显示新增界面
    handleAdd: function () {
      this.title = "新增";
      //弹出修改模态框
      this.editFormVisible = true;
      this.editForm = {
        //重置表单
        id: null,
        name: "",
        types_id: null
      };
    },
    //新增或者编辑
    editSubmit: function () {
      //this.$refs 拿到当前页面上的所有ref
      //this.$refs.editForm  找editForm
      this.$refs.editForm.validate((valid) => {//主动开启表单校验
        if (valid) {//如果校验没有问题
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            //开启按钮忙等
            this.editLoading = true;
            let para = Object.assign({}, this.editForm);
            //发起请求保存数据
            this.$http.put("/dicd", para)
                .then(result => {
                  //关闭按钮忙等
                  this.editLoading = false;
                  result = result.data//AjaxResult
                  if (result.success) {
                    //后端操作成功
                    this.$message({
                      message: result.message,
                      type: 'success'
                    });
                    //关闭模态框
                    this.editFormVisible = false;
                  } else {
                    this.$message({
                      message: result.message,
                      type: 'error'
                    });
                  }
                  ;
                  //重新查询所有数据
                  this.getDictionaryDetailsPlus()
                })
                .catch(result => {
                  //操作失败
                  this.$message({
                    message: result.data.message,
                    type: 'error'
                  });
                })
          }).catch(() => {
            //提交界面点击取消
            this.$message({
              message: "操作取消",
              type: 'info'
            });
          });
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //获取所有数据字典类型
    getDictionaryTypes(){
      this.$http.get("/dict")
      .then(result=>{
        this.dictionaryTypes=result.data
      })
    }
  },
  mounted() {
    this.getDictionaryDetails();
    this.getDictionaryTypes();
  }
}

</script>

<style scoped>

</style>